package website.haicheng.picturemanage;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import website.haicheng.picturemanage.commo.request.CommoRequest;
import website.haicheng.picturemanage.commo.request.TextRequest;
import website.haicheng.picturemanage.commo.response.TextResponse;
import website.haicheng.picturemanage.service.WeChatService;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author lhc
 */
@Slf4j
@RestController
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class PictureManageApplication {

    @Autowired
    private WeChatService weChatService;

    public static void main(String[] args) {
        SpringApplication.run(PictureManageApplication.class, args);
    }

    @GetMapping(value = "accountTest")
    public String accountTest(String signature, String timestamp, String nonce, String echostr) {
        String token = "lhc666";
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        String str = arr[0] + arr[1] + arr[2];
        String decStr = SecureUtil.sha1(str);
        boolean success = decStr.equals(signature);
        if (success) {
            log.info("账号检测;signature:{};timestamp:{};nonce:{};结果:[{}]", signature, timestamp, nonce, success);
            return echostr;
        }
        return "fail";
    }

    @PostMapping(value = "accountTest", produces = {"application/xml;charset=UTF-8"})
    public Object accountTest(HttpServletRequest request) {
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Document document = XmlUtil.readXML(inputStream);
        Node node = document.getChildNodes().item(0);
        CommoRequest message = XmlUtil.xmlToBean(node, TextRequest.class);
        System.out.println(message.toString());
        new Thread(() -> {
            String token = weChatService.getAccessToken();
            weChatService.deleteMenu(token);
        }).start();
        return new TextResponse(message.getFromUserName(), DateUtil.now());
    }
}
